//
//  NotificationModel.swift
//  mggz
//
//  Created by ShareAnimation on 2017/9/1.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Alamofire

class NotificationModel: NSObject {
    
    var messageTitle: String? //消息标题
    var createTime: Date? //创建时间
    var messageDescription: String? //消息详细描述
    var procNoticeId: String?
    var orderId: String?
    
    required init(rootDict: [String: AnyObject]) {
        self.messageTitle = rootDict["Title"] as? String
        self.messageDescription = rootDict["Description"] as? String
        self.procNoticeId = rootDict["ID"] as? String
        
        if let dateString = rootDict["CreateTime"] as? String {
            self.createTime = dateStringWithTToDate(dateString: dateString)
        }
        
        if let orderData = rootDict["OrderData"] as? [String: Any] {
            self.orderId = orderData["ID"] as? String
        }
    }
    
    /// 获取消息列表
    class func getMessageLists(_ start:Int, limit: Int = 25, completionHandler:@escaping (WWValueResponse<[NotificationModel]>) -> Void){
        let url = JsonAPIURL + "CallMethod"
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId else {
            return
        }
        let method = "KouFine.Handler.Core.AjaxOperate.FindPagingEntityData"
        let domain = "消息管理"
        let typeFullName = "KouFine.Common.MessageHub.Entity.ProcNotice"
        let orderManagerConfigId = "2737d08d-75ac-facb-64aa-60f8745992e3"
        let isQueryControl = "false"
        let sql = "(ProcNoticeDetailList.Any(NoticeEmpID == @EmpID))"
        let pageName = "MarTian.Notice"
        let controlName = ""
        
        let item = ["Name": "@EmpID", "Value":accountId, "Type":"Guid"]
        let sqlParam = ["Items":[item]]
        let sqlParamString = getJSONStringFromDictionary(dictionary: sqlParam as NSDictionary)
        
        let start = "\(start * limit)"
        let limit = "\(limit)"
        
        let params = ["Method":method, "domain": domain, "typeFullName":typeFullName, "orderManagerConfigId":orderManagerConfigId, "isQueryControl": isQueryControl, "sql":sql, "pageName":pageName, "controlName":controlName, "sqlParam":sqlParamString, "start":start, "limit": limit, "AccountId":accountId]
        Alamofire.request(url, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                if let value = response.result.value as? [String: AnyObject] {//第一步：判断数据不为nil，且为字典格式
                    //                    print(value)
                    print(value)
                    if let items = value["Items"] as? [[String: AnyObject]] {//第二部：判断字典里又items字段，且这个字典的value是数组，且数组里存放的是字典
                        var responseEntites = [NotificationModel]()
                        
                        for item in items {
                            let model = NotificationModel(rootDict: item)
                            responseEntites.append(model)
                        }
                        completionHandler(WWValueResponse.init(value: responseEntites, success: true))
                    }
                    else {
                        completionHandler(WWValueResponse.init(success: false, message: "items为空"))
                    }
                }
                else {
                    completionHandler(WWValueResponse.init(success: false, message: "数据不存在"))
                }
            }
            else {
                
                completionHandler(WWValueResponse.init(success: false, message: "网络访问错误"))
            }
        }
    }
    
    
}

enum NotificationType: String {
    case salaryHomeController = "民工工资-工资发放"
    case recordPathAbnormalController = "民工工资-轨迹异常"
    case recordSupplyFormController = "民工工资-打卡异常"
    case withdrawController = "民工工资-工资提现"
    case insureInfoController = "民工工资-保险绑定"
}
class NotificationTypeModel: NSObject {
    var type: NotificationType?
    var params: [String: Any]?
    
    required init(_ jsonDict: [String: Any]) {
        super.init()
        
        if let resultDict = jsonDict["Result"] as? [String: Any] {
            if let typeString = resultDict["Type"] as? String {
                let type = NotificationType.init(rawValue: typeString)
                self.type = type
            }
            
            if let paramDict = resultDict["Params"] as? [String: Any] {
                self.params = paramDict
            }
        }
    }
    
    
    class func getMessageJsonParams(_ procNoticeId: String, completionHandler:@escaping (WWValueResponse<NotificationTypeModel>) -> Void) {
        guard let httpHeader = WWUser.sharedInstance.mobile_cilent_headers else {
            return
        }
        guard let accountId = WWUser.sharedInstance.accountId else {
            return
        }
        
        let method = "KouFine.Common.MessageHub.Handler.AjaxProcNotice.GetProcNoticeJsonParams"
        
        let params = ["Method": method, "procNoticeId": procNoticeId, "AccountId":accountId]
        
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            
            if response.result.isSuccess {
                if let dict = response.result.value as? [String: Any] {
                    let status = dict["Status"] as? String
                    if status == "OK" {//OK的情况下type一定有值，ERROR情况下result为空，所以type也一定为空
                        let model = NotificationTypeModel.init(dict)
                        completionHandler(WWValueResponse.init(value: model, success: true))
                    }
                    else {
                        //status == ERROR的情况有两种。一种：出错了；另外一种：Result字段存在，但是value是空的。这种情况表示我们换一种方法去获取这条消息对应的数据（方法可以查看文档）
                        if dict["Result"] != nil {
                            
                            //model存在，但是model.type为nil就表示需要使用另外一种方法获取消息的信息。
                            let model = NotificationTypeModel.init(dict)
                            completionHandler(WWValueResponse.init(value: model, success: true))
                        }
                        else {
                            completionHandler(WWValueResponse.init(success: false, message: "获取消息信息错误！") )
                        }
                    }
                }
            }
            else {
                
                completionHandler(WWValueResponse.init(success: false, message: "网络访问错误！") )
            }
        }
        
    }
}

